import 'dart:async';

import 'package:dio/dio.dart';
import 'package:winkai/helper/iap/entity/a_iap_rsp.dart';
import 'package:winkai/helper/iap/entity/g_iap_rsp.dart';
import 'package:winkai/res/app_config.dart';

import 'entity/a_iap_req.dart';
import 'entity/g_iap_req.dart';

/// 内购验证接口
class IAPApi {
  late Dio _dio;

  factory IAPApi() {
    _singleton ??= IAPApi._();
    return _singleton!;
  }

  static IAPApi? _singleton;

  IAPApi._() {
    var baseUrl = AppConfig.iapApiHost;
    var options = BaseOptions(
      connectTimeout: const Duration(seconds: 30),
      receiveTimeout: const Duration(seconds: 30),
      baseUrl: baseUrl,
    );
    _dio = Dio(options);
  }

  ///校验苹果内购状态
  Future<AIAPRsp> verifyApplePurchase(AIAPReq params) async {
    Completer<AIAPRsp> completer = Completer();
    var response = _dio.post(
      '/v1/ios/receipt-verifier',
      data: params.toJson(),
    );
    response.catchError((e, stack) {
      if (!completer.isCompleted) {
        completer.completeError(e, stack);
      }
    });
    response.then((value) {
      if (!completer.isCompleted) {
        completer.complete(AIAPRsp.fromJson(value.data));
      }
    });
    return completer.future;
  }

  ///校验Google内购状态
  Future<GIAPRsp> verifyGooglePurchase(GIAPReq params) async {
    var res = await _dio.post(
      '/v1/google-play/receipt-verifier',
      data: params.toJson(),
    );
    return GIAPRsp.fromJson(res.data);
  }
}
